package cn.bugstack.springframework.beans.factory;

import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.PropertyValue;
import cn.bugstack.springframework.beans.PropertyValues;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import cn.bugstack.springframework.beans.factory.config.BeanFactoryPostProcessor;
import cn.bugstack.springframework.core.io.DefaultResourceLoader;
import cn.bugstack.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;


/**
 * 处理占位符配置
 */
public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {
    static final String DEFAULT_PLACEHOLDER_PREDFIX = "${";

    static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";

    String location;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        // 加载属性文件
        try{
            DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
            Resource resource = defaultResourceLoader.getResource(location);
            Properties properties = new Properties();
            properties.load(resource.getInputStream());

            String[] beanNames = beanFactory.getBeanDefinitionNames();
            for(String beanName:beanNames){
                BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

                PropertyValues propertyValues = beanDefinition.getPropertyValues();
                for(PropertyValue propertyValue : propertyValues.getPropertyValues()){
                    Object o = propertyValue.getValue();
                    if(!(o instanceof String)) continue;
                    String strVal = (String) o;

                    StringBuilder builder = new StringBuilder(strVal);
                    int start = strVal.indexOf(DEFAULT_PLACEHOLDER_PREDFIX);
                    int end = strVal.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
                    if(start != -1 && end != -0 && start < end){
                        String key = strVal.substring(start+2,end);
                        String val = properties.getProperty(key);
                        builder.replace(start,end+1,key);
                        propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(),builder.toString()));
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
